package com.controller;

import com.pojo.book;
import com.pojo.order;
import com.service.orderService;
import com.service.userService;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class purchaseServlet extends HttpServlet {
    private userService userService=new userService();
    private orderService orderService=new orderService();
    /**
     * 结算
     */

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Cookie[] cookies = req.getCookies();
        String uid=null;
        double userMoney=0.0;
        if(cookies==null||cookies.length<=0){
            out.print("未登录");
            return;
        }
        HttpSession session = req.getSession();
        Map<String, List<book>> cars = (Map<String, List<book>>) session.getAttribute("car");
        for (int i = 0; i < cookies.length; i++) {
            if(cookies[i].getName().equals("loginUser")){
                uid=cookies[i].getValue();
                break;
            }
        }
        //查看用户还有多少余额
        if(uid!=null){
            int userid = Integer.parseInt(uid);
            try {
                 userMoney = userService.getUserMoney(userid);
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            out.print("当前用户的余额为："+userMoney+"元<br/>");



        if(cars==null||cars.size()==0){
            out.print("购物车没有任何东西,下单失败！！！");
            return;
        }else{

                out.print("<table border=\"1\" width=\"650px\">");
                out.print("<tr><td colspan=\"5\" align=\"center\">您的购物车：</td></tr>");
                double result=0.0;

                out.print("<tr \"><td>序号&#160</td> <td>图书名称&#160&#160&#160&#160&#160&#160</td> <td>数目&#160&#160&#160&#160</td> <td>单价&#160&#160&#160</td> <td>总价&#160&#160&#160</td>   </tr><br/>");

                List<book> buycar = cars.get(uid);

                for (int i = 0; i < buycar.size(); i++) {
                    result+=buycar.get(i).getPrice()*buycar.get(i).getBookcount();
                    out.print("<tr>");
                    out.print("<td>"+buycar.get(i).getBookid()+"</td>");
                    out.print("<td>"+buycar.get(i).getBookName()+"</td>");
                    out.print("<td>"+buycar.get(i).getBookcount()+"</td>");
                    out.print("<td>"+buycar.get(i).getPrice()+"</td>");
                    out.print("<td>"+buycar.get(i).getPrice()*buycar.get(i).getBookcount()+"</td>");
                    out.print("</tr>");
                }
                out.print("<tr><td colspan=\"4\">总价为：</td><td>"+result+"</td></tr>");

                out.print("</table>");
                //余额足够，下单成功
                if(userMoney>=result){
                    String orderid = UUID.randomUUID().toString().replace("-", "");
                    Date date = new Date();
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");

                        String format = simpleDateFormat.format(date);

                    java.sql.Date sqlData=null;
                    try {
                        Date parse = simpleDateFormat.parse(format);
                        sqlData = new java.sql.Date(parse.getTime());

                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    for (int i = 0; i < buycar.size(); i++) {
                        String bookid = buycar.get(i).getBookid();
                        String bookName = buycar.get(i).getBookName();
                        int bookcount = buycar.get(i).getBookcount();
                        double price = buycar.get(i).getPrice();
                        try {
                            orderService.addOrder(new order(orderid,userid,bookid,bookcount,price*bookcount,sqlData));
                        } catch (SQLException e) {
                            e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
            }
                    try {
                        userService.decrUserMoney(userid,result);  //完成交易
                        session.invalidate(); //清空购物车session




                    } catch (SQLException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    req.getRequestDispatcher("orderSuccess.jsp").forward(req,resp);


                }else{
                    req.getRequestDispatcher("orderFalse.jsp").forward(req,resp);
                }



            }

        }













    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       this.doGet(req, resp);
    }
}
